package main

import (
	"encoding/json"
	"fmt"
	"gvms/common"
	"gvms/jvmsDb"
	"gvms/systemRegistry"
	"gvms/util"
	"gvms/window"
	"io"
	"net/http"
	"os"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"golang.org/x/sys/windows"
)

const jdkDefultVersionUrl = "https://gitee.com/huangdoudba/gvms/releases/download/v.0.1/sdk_version.json"

func main() {
	dir, _ := os.Getwd()
	jvmsDb.SetPath(dir)
	fmt.Println("读取注册表结束")
	db := jvmsDb.Opendb()
	fmt.Println("打开数据库结束")
	goHome := systemRegistry.QuerySystemGoHome()
	if goHome == "" {
		goHome = jvmsDb.GetSingleKey(db, "GO_HOME")
	}
	fmt.Println("读取java_home数据结束")
	util.SetVersionUrl(jvmsDb.GetSingleKey(db, "go_version_json"))
	if util.GetVersionUrl() == "" {
		util.SetVersionUrl(jdkDefultVersionUrl)
	}
	a := app.New()
	w := a.NewWindow("go版本控制")
	if goHome == "" {
		window.SelectJavaHomeDir(db, w, true, &goHome)
	}
	fmt.Println("读取go版本json地址结束")
	// 设置窗口内容并运行
	w.Resize(fyne.NewSize(500, 200))
	content := container.NewWithoutLayout()
	w.SetContent(content)
	jdkVersions := queryJdkVersion(w)
	var selectVersion string
	window.JvmsButton(&goHome, db, w, content, &selectVersion, jdkVersions)
	fmt.Println("发送请求查询go版本和下载连接结束")
	fmt.Println("窗体加载结束")
	content.Refresh()
	w.SetOnClosed(func() {
		defer db.Close()
	})
	w.ShowAndRun()
}

func queryJdkVersion(w fyne.Window) map[string]util.JDKVersion {
	resp, err := http.Get(util.GetVersionUrl())
	if err != nil {
		window.Message(w, "查询jdk版本失败")
	}
	if resp == nil {
		window.Message(w, "查询jdk版本失败")
		windows.Exit(1)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	var jdkVersions []util.JDKVersion
	er := json.Unmarshal(body, &jdkVersions)
	if er != nil {
		window.Message(w, "查询jdk版本失败")
	}
	m := make(map[string]util.JDKVersion)
	for _, jdkVersion := range jdkVersions {
		common.Set[string, util.JDKVersion](m, jdkVersion.Version, jdkVersion)
	}
	return m
}
